package com.jv.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jv.constant.SystemConstant;
import com.jv.entity.R;
import com.jv.entity.WxUserInfo;
import com.jv.properties.WeixinProperties;
import com.jv.service.IWxUserInfoService;
import com.jv.util.HttpClientUtil;
import com.jv.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;

/**
 * 微信用户的Controller
 * @author Jv
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private WeixinProperties weixinProperties;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private IWxUserInfoService wxUserInfoService;
    //微信用户登录
    @RequestMapping("/wxlogin")
    //返回的是json数据用RequestBody才能接收
    public R wxLogin(@RequestBody WxUserInfo wxUserInfo){
        System.out.println(wxUserInfo);
        String jscode2sessionUrl=weixinProperties.getJscode2sessionUrl()+"appid="+weixinProperties.getAppid()+
                "&secret="+weixinProperties.getSecret()+"&js_code="+wxUserInfo.getCode()+"&grant_type=authorization_code";
        System.out.println(jscode2sessionUrl);
        String result = httpClientUtil.sendHttpGet(jscode2sessionUrl);
        System.out.println(result);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.get("errmsg").toString().substring(18);
        System.out.println(openid);
        //插入用户到数据库中， 用户存在，更新用户、用户不存在，插入用户
        WxUserInfo resultWxUserInfo = wxUserInfoService.getOne(new QueryWrapper<WxUserInfo>().eq("openid", openid));
        if (resultWxUserInfo==null) {
            System.out.println("不存在，插入用户");
            wxUserInfo.setOpenid(openid);
            wxUserInfo.setLastLoginDate(new Date());
            wxUserInfo.setRegisterDate(new Date());
            wxUserInfoService.save(wxUserInfo);
        }else {
            System.out.println("存在，更新用户");
            resultWxUserInfo.setNickName(wxUserInfo.getNickName());
            resultWxUserInfo.setAvatarUrl(wxUserInfo.getAvatarUrl());
            resultWxUserInfo.setLastLoginDate(new Date());
            wxUserInfoService.updateById(resultWxUserInfo);
        }
        //利用jwt生成token返回前端
        String token = JwtUtils.createJWT(openid, wxUserInfo.getNickName(), SystemConstant.JWT_TTL);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        return R.ok(resultMap);
    }
}
